#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
安全查找器插件
"""

import sys
import hashlib
import time
import os
from pathlib import Path
from importlib.util import spec_from_file_location

# 导入统一的环境配置
from public.env_setup import setup_environment, ENV_CONFIG

# 使用统一的环境配置
ENV_CONFIG = setup_environment()

class SecureFinder:
    """安全查找器插件类"""
    
    def __init__(self):
        self.project_root = ENV_CONFIG['PROJECT_ROOT']
        self.mapping = {}
        self.package_attrs = {}
        
    def start(self) -> bool:
        """插件启动方法"""
        print("🔒 安全查找器")
        print("=" * 40)
        
        while True:
            print("\n请选择操作:")
            print("1. 📁 扫描目录")
            print("2. 🔍 查找模块")
            print("3. ✅ 检查完整性")
            print("4. 🔧 配置映射")
            print("5. ↩️ 返回主菜单")
            
            try:
                choice = input("\n请选择 (1-5): ").strip()
                
                if choice == "1":
                    self.scan_directory()
                elif choice == "2":
                    self.find_modules()
                elif choice == "3":
                    self.check_integrity()
                elif choice == "4":
                    self.configure_mapping()
                elif choice == "5":
                    return True
                else:
                    print("❌ 无效选项")
                    
            except KeyboardInterrupt:
                print("\n👋 返回主菜单")
                return True
            except Exception as e:
                print(f"❌ 错误: {e}")
                
        return True
    
    def scan_directory(self):
        """扫描目录"""
        print("\n📁 扫描目录:")
        
        target_dir = input("请输入要扫描的目录路径 (回车使用当前目录): ").strip()
        if not target_dir:
            target_dir = str(self.project_root)
        
        scan_path = Path(target_dir)
        if not scan_path.exists():
            print(f"❌ 目录不存在: {target_dir}")
            return
        
        print(f"扫描目录: {scan_path}")
        
        # 查找Python包
        packages = []
        for item in scan_path.iterdir():
            if item.is_dir() and (item / "__init__.py").exists():
                packages.append(item.name)
        
        print(f"找到 {len(packages)} 个Python包:")
        for pkg in packages:
            print(f"  📦 {pkg}")
            
        # 更新映射
        for pkg in packages:
            self.mapping[pkg] = str(scan_path / pkg)
            self.package_attrs[pkg] = {
                'checksum': self.calculate_hash(scan_path / pkg),
                'permissions': ['read'],
                'expires_at': None,
                'owner': 'admin',
                'last_check': time.time()
            }
        
        print("✅ 目录扫描完成")
    
    def find_modules(self):
        """查找模块"""
        print("\n🔍 查找模块:")
        
        if not self.mapping:
            print("❌ 没有配置模块映射，请先扫描目录")
            return
        
        module_name = input("请输入要查找的模块名: ").strip()
        
        if module_name in self.mapping:
            module_path = Path(self.mapping[module_name])
            print(f"✅ 找到模块: {module_name}")
            print(f"  路径: {module_path}")
            print(f"  存在: {module_path.exists()}")
            
            if module_name in self.package_attrs:
                attrs = self.package_attrs[module_name]
                print(f"  最后检查: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(attrs['last_check']))}")
                print(f"  权限: {attrs['permissions']}")
        else:
            print(f"❌ 模块 {module_name} 未找到")
    
    def check_integrity(self):
        """检查完整性"""
        print("\n✅ 检查完整性:")
        
        if not self.mapping:
            print("❌ 没有配置模块映射")
            return
        
        for module_name, module_path in self.mapping.items():
            path = Path(module_path)
            print(f"检查模块: {module_name}")
            
            if not path.exists():
                print(f"  ❌ 路径不存在: {module_path}")
                continue
            
            current_hash = self.calculate_hash(path)
            stored_hash = self.package_attrs.get(module_name, {}).get('checksum')
            
            if stored_hash and current_hash != stored_hash:
                print(f"  ❌ 完整性检查失败")
            else:
                print(f"  ✅ 完整性检查通过")
    
    def configure_mapping(self):
        """配置映射"""
        print("\n🔧 配置映射:")
        
        print("当前映射:")
        for module_name, module_path in self.mapping.items():
            print(f"  {module_name} -> {module_path}")
        
        print("\n操作选项:")
        print("1. 添加映射")
        print("2. 删除映射")
        print("3. 清空所有映射")
        
        choice = input("请选择操作 (1-3): ").strip()
        
        if choice == "1":
            module_name = input("模块名: ").strip()
            module_path = input("模块路径: ").strip()
            
            if module_name and module_path:
                self.mapping[module_name] = module_path
                self.package_attrs[module_name] = {
                    'checksum': self.calculate_hash(Path(module_path)),
                    'permissions': ['read'],
                    'expires_at': None,
                    'owner': 'admin',
                    'last_check': time.time()
                }
                print("✅ 映射添加成功")
        
        elif choice == "2":
            module_name = input("要删除的模块名: ").strip()
            if module_name in self.mapping:
                del self.mapping[module_name]
                if module_name in self.package_attrs:
                    del self.package_attrs[module_name]
                print("✅ 映射删除成功")
            else:
                print("❌ 模块不存在")
        
        elif choice == "3":
            self.mapping.clear()
            self.package_attrs.clear()
            print("✅ 所有映射已清空")
    
    def calculate_hash(self, path):
        """计算文件或目录的哈希值"""
        if path.is_file():
            try:
                with open(path, 'rb') as f:
                    return hashlib.md5(f.read()).hexdigest()
            except Exception:
                return None
        elif path.is_dir():
            try:
                # 计算目录下所有Python文件的哈希
                hashes = []
                for file_path in path.rglob('*.py'):
                    with open(file_path, 'rb') as f:
                        hashes.append(hashlib.md5(f.read()).hexdigest())
                return hashlib.md5(''.join(hashes).encode()).hexdigest()
            except Exception:
                return None
        return None

# 测试
test_mapping = {
    'my_package': 'D:/AI/scripts/Scripts/my_package'
}

# 创建测试包
import os
os.makedirs('my_package', exist_ok=True)
with open('my_package/__init__.py', 'w') as f:
    f.write('print("加载安全包"); version = "2.0.0"')

# 注意：SecureFinder不是MetaPathFinder，不应该注册到sys.meta_path
# finder = SecureFinder()
# sys.meta_path.insert(0, finder)

print("SecureFinder 已准备就绪")
print("这是一个安全查找工具，不是模块查找器...") 